extends Node2D

var qt: QuadTree # 四叉树实例
var founds = [] # 查询结果
var rect = Rect2(Vector2(0, 0), Vector2(0, 0)) # 查询范围

const colors = [Color("f0f2e4"), Color("f5d6d6"), Color("b0f1c6"), Color("24acf2"), Color("f9d987")]


func _ready() -> void:
	var boundary = Rect2(0, 0, 400, 400)
	qt = QuadTree.new(boundary, 2)

func _input(event: InputEvent) -> void:
	if event is InputEventMouseButton and event.is_pressed():
		founds = []
		if event.button_index == MOUSE_BUTTON_LEFT:
			var obj = QuadTreeObj.new()
			obj.position = event.global_position
			qt.insert(obj)
			queue_redraw()
		elif event.button_index == MOUSE_BUTTON_RIGHT:
			var point = event.global_position
			rect = Rect2(point - Vector2(50, 50), Vector2(100, 100))
			qt.query(rect, founds)
			queue_redraw()

func _draw() -> void:
	# 绘制四叉树
		draw_tree(qt)
		# 绘制查询结果
		for obj in founds:
			draw_circle(obj.position, 5, Color.YELLOW)
		# 绘制查询范围
		draw_rect(rect, Color(1, 0, 0, .1), true)
		
# 递归渲染所有四叉树范围及其节点
func draw_tree(tree: QuadTree, depth: int = 0):
	draw_rect(tree.boundary.grow(-2), colors[depth], true)
	if tree.divided:
		draw_tree(tree.northeast, depth + 1)
		draw_tree(tree.northwest, depth + 1)
		draw_tree(tree.southeast, depth + 1)
		draw_tree(tree.southwest, depth + 1)
	for obj in tree.objs:
		draw_circle(obj.position, 4, Color.MEDIUM_VIOLET_RED)
